package com.sky.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Slf4j
@RequiredArgsConstructor
@Service
public class DishServiceImpl implements DishService {

    private final DishMapper dishMapper;

    private final DishFlavorMapper dishFlavorMapper;

    private final SetmealMapper setMealMapper;

    private final SetmealDishMapper setmealDishMapper;

    @Transactional
    @Override
    public void create(DishDTO dishDTO) {
        //属性校验
        check(dishDTO);
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (Objects.nonNull(flavors) && !flavors.isEmpty()) {
            flavors.forEach(e -> e.setDishId(dish.getId()));
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public PageResult readPage(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> dishPage = dishMapper.selectPage(dishPageQueryDTO);
        return new PageResult(dishPage.getTotal(), dishPage.getResult());
    }

    @Transactional
    @Override
    public void deleteByIds(List<Long> ids) {
        //启用的套餐不能被删除
        Integer count = dishMapper.selectCountByIdsAndStatus(ids, StatusConstant.ENABLE);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);
    }

    @Override
    public DishVO infoById(Long id) {
        DishVO dishVO = dishMapper.selectById(id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishId(id);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    @Transactional
    @Override
    public void updateById(DishDTO dishDTO) {
        //属性校验
        check(dishDTO);
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateById(dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //跟新口味
        dishFlavorMapper.deleteByDishIds(Collections.singletonList(dish.getId()));
        if (Objects.nonNull(flavors) && !flavors.isEmpty()) {
            flavors.forEach(e -> e.setDishId(dish.getId()));
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public List<Dish> readListByCategoryId(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .build();
        return dishMapper.selectByCategoryId(dish);
    }

    @Transactional
    @Override
    public void status(Integer status, Long id) {
        //菜品停售
        dishMapper.updateByStatus(status, id);
        //得到对应的套餐id集合
        List<SetmealDish> list = setmealDishMapper.selectSetmealByDishId(id);
        if (list.size()>0){
            List<Long> ids = new ArrayList<>();
            list.forEach(e->ids.add(e.getSetmealId()));
            //对应的套餐停售
            setMealMapper.updateStatus(StatusConstant.DISABLE,ids);
        }
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.selectByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 属性校验
     */
    private void check(DishDTO dishDTO) {
        //菜品名称校验
        String name = dishDTO.getName();
        if (Objects.isNull(name) || !name.matches("^[\\u4E00-\\u9FA5a-zA-Z0-9]{2,20}$")) {
            throw new BaseException(MessageConstant.DISH_NAME_IS_ERROR);
        }
        //菜品名称唯一校验
        Integer count = dishMapper.selectCount(dishDTO);
        if (count > 0) {
            throw new BaseException(MessageConstant.DISH_NAME_IS_DUPLICATE);
        }
        //口味最多4种
        if (dishDTO.getFlavors().size() > 4) {
            throw new BaseException(MessageConstant.TASTE_OF_DISHES_EXCEEDS_THE_LIMIT);
        }
        //价格长度1-8
        BigDecimal price = dishDTO.getPrice();
        if (!price.toString().matches("^\\d{1,8}(\\.\\d{1,2})?$")) {
            throw new BaseException(MessageConstant.DISH_PRICE_FORMAT_ERROR);
        }
        String description = dishDTO.getDescription();
        if (!description.matches("^[\\u4E00-\\u9FA5a-zA-Z0-9]{0,200}$")) {
            throw new BaseException(MessageConstant.DISH_DESCRIPTION_ERROR);
        }
    }
}
